package com.alien.admin.modules.message.service.impl;

import com.alien.admin.modules.message.domain.NotifyAnnounce;
import com.alien.admin.modules.message.domain.NotifyAnnounceUser;
import com.alien.admin.modules.message.repository.NotifyAnnounceRepository;
import com.alien.admin.modules.message.repository.NotifyAnnounceUserRepository;
import com.alien.admin.modules.message.service.MessageNotifier;
import com.alien.admin.modules.security.service.dto.JwtUserDto;
import com.alien.admin.utils.MessageConstants;
import com.alien.admin.utils.SecurityUtils;
import com.alien.admin.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

@Service
public class MessageNotifierImpl implements MessageNotifier {
    @Autowired
    private NotifyAnnounceRepository notifyAnnounceRepository;
    @Autowired
    private NotifyAnnounceUserRepository notifyAnnounceUserRepository;

    @Override
    public void sendInfoMessage(Long userId, String title, String message) {
        sendInfoMessage(userId, title, message, "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendInfoMessage(Long userId, String title, String message, String router) {
        NotifyAnnounce notifyAnnounce = new NotifyAnnounce();
        notifyAnnounce.setSenderId(-1L);
        notifyAnnounce.setTitle(title);
        notifyAnnounce.setMessage(message);
        notifyAnnounce.setIsHtml(false);
        notifyAnnounce.setRouter(router);
        notifyAnnounce.setType(MessageConstants.MESSAGE_TYPE_INFO);
        notifyAnnounce.setDuration(0L);

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        notifyAnnounce.setCreateTime(timestamp);

        notifyAnnounce.setCreateBy(getSenderUser());
        notifyAnnounce = notifyAnnounceRepository.save(notifyAnnounce);

        NotifyAnnounceUser notifyAnnounceUser = new NotifyAnnounceUser();
        notifyAnnounceUser.setAnnounceId(notifyAnnounce.getId());
        notifyAnnounceUser.setRecipientId(userId);
        notifyAnnounceUser.setCreateTime(timestamp);
        notifyAnnounceUser.setState(false);
        notifyAnnounceUserRepository.save(notifyAnnounceUser);
    }

    String getSenderUser() {
        String createBy;
        try {
            JwtUserDto jwtUserDto = (JwtUserDto)SecurityUtils.getCurrentUser();
            createBy = jwtUserDto.getUser().getNickName();
        } catch (Exception e) {
            createBy = "系统";
        }
        return createBy;
    }
}
